<template>
	<div class="shelf-footer" v-show="isEditMode">
		<div class="shelf-footer-tab-wrapper" v-for="item in tabs" :key="item.index" @click="onTabClick(item)">
			<div class="shelf-footer-tab" :class="{'is-selected': isSelected}">
				<div class="icon-private tab-icon" v-if="item.index === 1 && !isPrivate"></div>
				<div class="icon-private-see tab-icon" v-if="item.index === 1 && isPrivate"></div>
				<div class="icon-download tab-icon" v-if="item.index === 2 && !isDownload"></div>
				<div class="icon-download-remove tab-icon" v-if="item.index === 2 && isDownload"></div>
				<div class="icon-move tab-icon" v-if="item.index === 3"></div>
				<div class="icon-shelf tab-icon" v-if="item.index === 4"></div>
				<div class="tab-text" :class="{'remove-text': item.index === 4}">{{label(item)}}</div>
			</div>
		</div>
	</div>
</template>

<script>
import { download } from '../../api/store'
import { removeLocalForage } from '../../utils/localForage'
import { removeLocalStorage, saveBookShelf } from '../../utils/localStorage'
import { storeShelfMixin } from '../../utils/mixin'

export default {
	mixins: [storeShelfMixin],
	computed: {
		isSelected() { // 是否选中
			return this.shelfSelected && this.shelfSelected.length > 0
		},
		// 按钮
		tabs() {
			return [
				{ // 私密阅读
					label: this.$t('shelf.private'),
					label2: this.$t('shelf.noPrivate'),
					index: 1
				},
				{
					// 开启离线
					label: this.$t('shelf.download'),
					label2: this.$t('shelf.delete'),
					index: 2
				},
				{
					// 移动到
					label: this.$t('shelf.move'),
					index: 3
				},
				{
					// 移出书架
					label: this.$t('shelf.remove'),
					index: 4
				}
			]
		},
		isPrivate() { // 判断是否为私密阅读
			if (!this.isSelected) {
				return false
			} else {
				return this.shelfSelected.every(item => item.private)
			}
		},
		isDownload() { // 判断是否离线缓存
			if (!this.isSelected) {
				return false
			} else {
				return this.shelfSelected.every(item => item.cache)
			}
		}
	},
	data() {
		return {
			popupMenu: null
		}
	},
	methods: {
		async downloadSelectedBook() {
			for (let i = 0; i < this.shelfSelected.length; i++) {
				await this.downloadBook(this.shelfSelected[i])
						.then(book => {
							book.cache = true
						})
			}
		},
		downloadBook(book) {
			let text = ''
			const toast = this.toast({
				text
			})
			toast.continueShow()
			return new Promise((resolve, reject) => {
				download(book, book => {
					// 下载完成后，移除toast组件
					// setTimeout(() => {
					// 	toast.remove()
					// }, 1)
					// setTimeout(this.removeLocationView(), 1)
					toast.remove()
					resolve(book)
				}, reject, progressEvent => {
					// 定义下载进度百分比
					const progress = Math.floor(progressEvent.loaded / progressEvent.total * 100) + '%'
					text = this.$t('shelf.progressDownload').replace('$1', `${book.fileName}.epub(${progress})`)
					toast.updateText(text)
				})
			})
		},
		removeSelectedBook() {
			Promise.all(this.shelfSelected.map(book => this.removeBook(book)))
						 .then(books => { // 返回结果集
							 	books.map(book => {
									book.cache = false
								})
								// 保存到localStorage中
								saveBookShelf(this.shelfList)
								// console.log('ok')
								this.simpleToast(this.$t('shelf.removeDownloadSuccess'))
						 	})
		},
		removeBook(book) {
			return new Promise((resolve, reject) => {
				removeLocalStorage(`${book.categoryText}/${book.fileName}-info`)
				removeLocalForage(`${book.fileName}`)
				resolve(book)
			})
		},
		hidePopup() { // 隐藏组件
			this.popupMenu.hide()
		},
		onComplete() {
			this.hidePopup()
			// 关闭编辑
			this.setIsEditMode(false)
			// 保存到LocalStorage中
			saveBookShelf(this.shelfList)
			// 弹窗提示
		},
		setPrivate() {
			let isPrivate
			if (this.isPrivate) {
				isPrivate = false
			} else {
				isPrivate = true
			}
			this.shelfSelected.forEach(book => {
				book.private = isPrivate
			})
			this.onComplete()
			if (isPrivate) {
				this.simpleToast(this.$t('shelf.setPrivateSuccess'))
			} else {
				this.simpleToast(this.$t('shelf.closePrivateSuccess'))
			}
		},
		async setDownload() {
			this.onComplete()
			if (this.isDownload) {
				// 移除书籍
				// console.log('移除成功')
				this.removeSelectedBook()
			} else { // 下载成功
				// async await 转换任务为同步任务
				await this.downloadSelectedBook()
				// 保存到localStorage中
				saveBookShelf(this.shelfList)
				this.simpleToast(this.$t('shelf.setDownloadSuccess'))
			}
		},
		removeSelected() {
			this.shelfSelected.forEach(selected => {
				this.setShelfList(this.shelfList.filter(book => book !== selected))
			})
			// 更新Vuex中状态
			this.setShelfSelected([])
			this.onComplete()
		},
		showPrivate() {
			this.popupMenu = this.popup({
				title: this.isPrivate ? this.$t('shelf.closePrivateTitle') : this.$t('shelf.setPrivateTitle'),
				btn: [
					{
						text: this.isPrivate ? this.$t('shelf.close') : this.$t('shelf.open'),
						click: () => {
							this.setPrivate()
						}
					},
					{
						text: this.$t('shelf.cancel'),
						click: () => {
							this.hidePopup()
						}
					}
				]
			}).show()
		},
		showDownload() {
			this.popupMenu = this.popup({
				title: this.isDownload ? this.$t('shelf.removeDownloadTitle') : this.$t('shelf.setDownloadTitle'),
				btn: [
					{
						text: this.isDownload ? this.$t('shelf.delete') : this.$t('shelf.open'),
						click: () => {
							this.setDownload()
						}
					},
					{
						text: this.$t('shelf.cancel'),
						click: () => {
							this.hidePopup()
						}
					}
				]
			}).show()
		},
		showRemove() {
			let title
			if (this.shelfSelected.length === 1) { // 移除一本书
				title = this.$t('shelf.removeBookTitle').replace('$1', `《${this.shelfSelected[0].title}》`)
			} else { // 移除多本书
				title = this.$t('shelf.removeBookTitle').replace('$1', this.$t('shelf.selectedBooks'))
			}
			this.popupMenu = this.popup({
				title: title,
				btn: [
					{
						text: this.$t('shelf.open'),
						type: 'danger',
						click: () => {
							this.removeSelected()
						}
					},
					{
						text: this.$t('shelf.cancel'),
						click: () => {
							this.hidePopup()
						}
					}
				]
			}).show()
		},
		onTabClick(item) {
			if (!this.isSelected) {
				return
			}
			switch (item.index) {
				case 1:
					// 私密阅读
					this.showPrivate()
					break
				case 2:
					this.showDownload()
					break
				case 3:
					this.dialog().show()
					break
				case 4:
					this.showRemove()
					break
				default:
					break
			}
		},
		label(item) {
			switch (item.index) {
				case 1:
					return this.isPrivate ? item.label2 : item.label
				case 2:
					return this.isDownload ? item.label2 : item.label
				default:
					return item.label
			}
		}
	}
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
	@import "../../assets/styles/global.scss";
	.shelf-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 120;
		display: flex;
		width: 100%;
		height: px2rem(48);
		background: white;
		box-shadow: 0 px2rem(-2) px2rem(4) 0 rgba(0, 0, 0, .1);
		.shelf-footer-tab-wrapper {
			flex: 1;
			width: 25%;
			height: 100%;
			.shelf-footer-tab {
				width: 100%;
				height: 100%;
				opacity: .5;
				@include columnCenter;
				&.is-selected {
					opacity: 1;
				}
				.tab-icon {
					font-size: px2rem(20);
					color: #666;
				}
				.tab-text {
					margin-top: px2rem(5);
					font-size: px2rem(12);
					color: #666;
					&.remove-text {
						color: $color-pink;
					}
				}
				.icon-shelf {
					color: $color-pink;
				}
			}
		}
	}
</style>
